package com.xc.freeapp.filter;

import java.lang.reflect.Method;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;

import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.WebRequest;

import com.alibaba.fastjson.JSONArray;
import com.xc.freeapp.bean.AuthInfo;
import com.xc.freeapp.common.ResponseBean;
import com.xc.freeapp.exception.BaseException;
import com.xc.freeapp.redis.VerificationCodeDao;
import com.xc.freeapp.util.AuthUtil;
import com.xc.freeapp.util.JsonUtil;
import com.xc.freeapp.util.JwtUtil;
import com.xc.freeapp.util.TokenAnnotation;
/**
 * 请求拦截处理类
 * 
 * 
 */
public class TokenInterceptor implements MethodBeforeAdvice   {
	private Logger log = Logger.getLogger(this.getClass());
	@Autowired
	VerificationCodeDao verificationCodeDaoImpl;
	public void before(Method method, Object[] args, Object target)
			throws Throwable {
		TokenAnnotation tokenAnnotation= method.getAnnotation(TokenAnnotation.class);
		if(tokenAnnotation==null){
			throw new BaseException("404");
		}
    	if(tokenAnnotation!=null&&tokenAnnotation.required()){
    		HttpServletRequest curRequest =((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    		String token = AuthUtil.getToken(curRequest);
    		AuthInfo authInfo = AuthUtil.getAuthInfo(curRequest);
    		Map<String, Object> map = JwtUtil.vifity(token);
			log.info("token信息为:" + map);
			
			if(map==null||map.get("userId")==null||authInfo==null||!map.get("userId").equals(authInfo.getUserIntId())){
				throw new BaseException("419");
			}
			String redistoken = verificationCodeDaoImpl.get("token_"+map.get("userId"));
			if(redistoken!=null&&redistoken.equals(token)){
				log.info("验证通过");
			}else{
				log.info("redis验证不通过");
				throw new BaseException("419");
			}
    	}
	}
}